interface Options {
  url: string
  data?: any
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  [key: string]: any
}

type Serialize = 'json' | 'text' | 'blob' | 'arrayBuffer'
type Headers = {
  [index: string]: string
}

export default function (options: Options, serialize: Serialize = 'json') {
  const { url, method, data, timeout=30000 } = options
  const headers: Headers = {
    'Content-Type': 'application/json',
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
  }
  const controller = new AbortController()
  const tid = setTimeout(() => {
    console.log('被动关闭')
    controller.abort();
  }, timeout);
  return fetch(url, {
    headers,
    method: method || 'GET',
    body: JSON.stringify(data),
    signal: controller.signal
  })
    .then((res) => {
      return res[serialize]()
    })
    .then((data) => {
      clearTimeout(tid)
      return data
    })
    .catch((err) => {
      console.log(err)
      clearTimeout(tid)
      return Promise.reject(err)
    })
}
